package com.alibaba.citrus.cr.platform.enhance.dto;

import com.alibaba.cz.base.tool.Nullable;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * 这其实是菜单树
 *
 * @author luyan
 * @since 2019/12/26 16:11
 */
@Getter
@Setter
@ToString
public class PermissionTreePortalResp {
    private String id;
    private String code;
    private String name;
    private String parentId;
    /**
     * from portalMenu
     */
    private String permissionId;
    /**
     * from portalMenu
     */
    private Integer weight;
    /**
     * 是否由权限，当在角色里面返回时有用，其他情况无用，标识角色是否已经拥有这个权限
     */
    private Boolean having;
    /**
     * 菜单类型
     *
     */
    private Integer type;
    private List<PermissionTreePortalResp> children;

    public void sort() {
        if (children != null ) {
            children.sort(Comparator.comparingInt(item -> Nullable.of(item).map(PermissionTreePortalResp::getWeight).orElse(0)));
            for (PermissionTreePortalResp child : children) {
                child.sort();
            }
        }
    }

    public void markHaving(List<PermissionTreePortalResp> permissionList) {
        for (PermissionTreePortalResp that : permissionList) {
            if (this.isSameThat(that)) {
                this.having = true;
            }
        }
        if (children != null) {
            for (PermissionTreePortalResp child : children) {
                child.markHaving(permissionList);
            }
        }
    }

    public boolean isSameThat(PermissionTreePortalResp that) {
        if (that == null) {
            return false;
        }
        return Objects.equals(that.getId(), id) && Objects.equals(that.getCode(), code);
    }

    public List<PermissionTreePortalResp> getChildren() {
//        if (children == null) {
//            this.children = new ArrayList<>();
//        }
        return this.children;
    }
}
